//
//  BVModifyAddressViewController.m
//  BuyVegetables
//
//  Created by 叶思超 on 15/10/13.
//  Copyright (c) 2015年 叶思超. All rights reserved.
//

#import "BVModifyAddressViewController.h"
#import "BVConst.h"
#import "UIView+Extension.h"
#import "BVReceviceAddress.h"
#import "HttpTool.h"
#import "BVBMKMapViewController.h"
#import "MBProgressHUD.h"
#import "BVBusinessModelNSObject.h"
#import "BVBusinessModelData.h"

@interface BVModifyAddressViewController () <UITextFieldDelegate,UIPickerViewDataSource, UIPickerViewDelegate,BVBMKMapViewControllerDelegate>
/**   姓名*/
@property (nonatomic, strong) UITextField *nameF;
/**   手机号*/
@property (nonatomic, strong) UITextField *phoneF;
/**   地址*/
@property (nonatomic, strong) UITextField *addressF;
/**   详细地址*/
@property (nonatomic, strong) UITextField *detailAddressF;
/**   创建pickView*/
@property (nonatomic, strong) UIPickerView *BusinessPickerViewX;
/**   商圈*/
@property (nonatomic ,strong) UITextField * BusinessFX;
/**   商圈button*/
@property (nonatomic ,strong) UIButton * BusinessFB;
/**   商圈选择父视图*/
@property (nonatomic, strong) UIView *citySelectedX;
/**   存放所有商圈信息*/
@property (nonatomic, strong) NSMutableArray *BusinessArryX;
/**   存放所有商圈ID*/
@property (nonatomic, strong) NSMutableArray *BusinessArryXID;
/**   商圈ID*/
@property (nonatomic,   copy)NSString * SID;

@end

@implementation BVModifyAddressViewController

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.addressF resignFirstResponder];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.nameF becomeFirstResponder];
    
    //请求商圈内容
    [self getShangQuan];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 设置导航栏
    // 设置导航栏目
    [self setupNav];
    
    // 设置UI
    [self setupUI];
    
    //注册键盘出现的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cancelBtnClick) name:UIKeyboardWillShowNotification object:nil];
}

#pragma mark -- 设置UI
- (void)setupUI {
    // 联系人标签
    UILabel *contactLabel = [[UILabel alloc] init];
    contactLabel.frame = CGRectMake(10, 84, 75, 40);
    contactLabel.backgroundColor = [UIColor whiteColor];
    contactLabel.font = [UIFont systemFontOfSize:15];
    contactLabel.text = @" 联 系 人 :";
    contactLabel.textColor = BVBaseTextBlackColor;
    [self.view addSubview:contactLabel];
    
    // 联系人姓名
    self.nameF = [[UITextField alloc] init];
    self.nameF.frame = CGRectMake(CGRectGetMaxX(contactLabel.frame), contactLabel.y, BVScreenW - CGRectGetMaxX(contactLabel.frame) - 10, 40);
    self.nameF.textColor = BVBaseTextBlackColor;
    self.nameF.font = [UIFont systemFontOfSize:15];
    self.nameF.backgroundColor = [UIColor whiteColor];
    self.nameF.text = self.receviceAddress.contact;
    [self.view addSubview:self.nameF];
    
    // 分割线一
    UIView *oneSeparatorLine = [[UIView alloc] init];
    oneSeparatorLine.frame = CGRectMake(10, CGRectGetMaxY(contactLabel.frame), BVScreenW - 2 * 10, 0.5);
    oneSeparatorLine.backgroundColor = BVTextLightGrayColor;
    [self.view addSubview:oneSeparatorLine];
    
    // 联系方式标签
    UILabel *telLabel = [[UILabel alloc] init];
    telLabel.frame = CGRectMake(10, CGRectGetMaxY(oneSeparatorLine.frame), 75, 40);
    telLabel.font = [UIFont systemFontOfSize:15];
    telLabel.text = @" 联系方式:";
    telLabel.backgroundColor = [UIColor whiteColor];
    telLabel.textColor = BVBaseTextBlackColor;
    [self.view addSubview:telLabel];
    
    // 联系方式
    self.phoneF = [[UITextField alloc] init];
    self.phoneF.frame = CGRectMake(CGRectGetMaxX(telLabel.frame), telLabel.y, BVScreenW - CGRectGetMaxX(telLabel.frame) - 10, 40);
    self.phoneF.textColor = BVBaseTextBlackColor;
    self.phoneF.backgroundColor = [UIColor whiteColor];
    self.phoneF.font = [UIFont systemFontOfSize:15];
    self.phoneF.text = self.receviceAddress.mobile;
    [self.view addSubview:self.phoneF];
    
    // 分割线二
    UIView *twoSeparatorLine = [[UIView alloc] init];
    twoSeparatorLine.frame = CGRectMake(10, CGRectGetMaxY(self.phoneF.frame), BVScreenW - 2 * 10, 0.5);
    twoSeparatorLine.backgroundColor = BVTextLightGrayColor;
    [self.view addSubview:twoSeparatorLine];
    
    // 收货地址标签
    UILabel *addressLabel = [[UILabel alloc] init];
    addressLabel.frame = CGRectMake(10, CGRectGetMaxY(twoSeparatorLine.frame), 75, 40);
    addressLabel.backgroundColor = [UIColor whiteColor];
    addressLabel.textColor = BVBaseTextBlackColor;
    addressLabel.text = @" 收货地址:";
    addressLabel.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:addressLabel];
    
    // 获取收货地址
    self.addressF = [[UITextField alloc] init];
    self.addressF.frame = CGRectMake(CGRectGetMaxX(addressLabel.frame), addressLabel.y, BVScreenW - CGRectGetMaxX(addressLabel.frame) - 10, 40);
    self.addressF.textColor = BVBaseTextBlackColor;
    self.addressF.backgroundColor = [UIColor whiteColor];
    self.addressF.font = [UIFont systemFontOfSize:15];
    self.addressF.text = self.receviceAddress.receive_address;
    self.addressF.delegate = self;
    [self.view addSubview:self.addressF];
    
    // 分割线三
    UIView *threSeparatorLine = [[UIView alloc] init];
    threSeparatorLine.frame = CGRectMake(10, CGRectGetMaxY(self.addressF.frame), BVScreenW - 2 * 10, 0.5);
    threSeparatorLine.backgroundColor = BVTextLightGrayColor;
    [self.view addSubview:threSeparatorLine];
    
    // 详细地址标签
    UILabel *addressDetailLabel = [[UILabel alloc] init];
    addressDetailLabel.frame = CGRectMake(10, CGRectGetMaxY(threSeparatorLine.frame), 75, 40);
    addressDetailLabel.backgroundColor = [UIColor whiteColor];
    addressDetailLabel.textColor = BVBaseTextBlackColor;
    addressDetailLabel.text = @" 详细地址:";
    addressDetailLabel.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:addressDetailLabel];
    // 详细地址
    self.detailAddressF = [[UITextField alloc] init];
    self.detailAddressF.frame = CGRectMake(CGRectGetMaxX(telLabel.frame), CGRectGetMaxY(threSeparatorLine.frame), BVScreenW - CGRectGetMaxX(telLabel.frame) - 10, 40);
    self.detailAddressF.textColor = BVBaseTextBlackColor;
    self.detailAddressF.backgroundColor = [UIColor whiteColor];
    self.detailAddressF.font = [UIFont systemFontOfSize:15];
    self.detailAddressF.text = self.receviceAddress.detailed_address;
    [self.view addSubview:self.detailAddressF];
    
    // 分割线四
    UIView *fourSeparatorLine = [[UIView alloc] init];
    fourSeparatorLine.frame = CGRectMake(10, CGRectGetMaxY(threSeparatorLine.frame) + 40, BVScreenW - 2 * 10, 0.5);
    fourSeparatorLine.backgroundColor = BVTextLightGrayColor;
    [self.view addSubview:fourSeparatorLine];
    
    //商圈选择标签
    UILabel * BusinessCircle = [[UILabel alloc]init];
    BusinessCircle.frame = CGRectMake(10, CGRectGetMaxY(fourSeparatorLine.frame), 75, 40);
    BusinessCircle.text = @" 商       圈:";
    BusinessCircle.textColor = BVBaseTextBlackColor;
    BusinessCircle.backgroundColor = [UIColor whiteColor];
    BusinessCircle.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:BusinessCircle];

    //商圈textField
    self.BusinessFB = [[UIButton alloc]init];
    self.BusinessFB.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
    self.BusinessFB.backgroundColor = [UIColor whiteColor];
    [self.BusinessFB setTitleColor:BVBaseTextBlackColor forState:UIControlStateNormal];
    self.BusinessFB.titleLabel.font = [UIFont systemFontOfSize:15];
    self.BusinessFB.frame = CGRectMake(CGRectGetMaxX(BusinessCircle.frame), BusinessCircle.y, BVScreenW - CGRectGetMaxX(addressLabel.frame) - 10, 40);
    [self.BusinessFB addTarget:self action:@selector(seten) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.BusinessFB];
    
    NSString * FBtext = self.receviceAddress.business_circle;
    if (FBtext.length == 0) {
        [self.BusinessFB setTitle:@" 请选择商圈:" forState:UIControlStateNormal];
    }else{
        [self.BusinessFB setTitle:FBtext forState:UIControlStateNormal];
    }
    self.SID = self.receviceAddress.trade_id;

    // 确定添加
    UIButton *confirmButton = [[UIButton alloc] init];
    confirmButton.frame = CGRectMake(10, CGRectGetMaxY(BusinessCircle.frame) + 20, BVScreenW - 2 * 10, 40);
    confirmButton.backgroundColor = BVBaseOrangeColor;
    confirmButton.titleLabel.font = [UIFont systemFontOfSize:20];
    [confirmButton setTitle:@"确     定" forState:UIControlStateNormal];
    [confirmButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [confirmButton addTarget:self action:@selector(confirmClick) forControlEvents:UIControlEventTouchUpInside];
    confirmButton.layer.masksToBounds = YES;
    confirmButton.layer.cornerRadius = 4;
    confirmButton.layer.borderColor = [UIColor whiteColor].CGColor;
    confirmButton.layer.borderWidth = 1;
    [self.view addSubview:confirmButton];
}

-(void)seten{
    [self.view endEditing:YES];
    [self setpick];
}
#pragma mark -- 设置商圈pick
-(void)setpick{
    
    if(_citySelectedX) return;
    
    _citySelectedX = [[UIView alloc] init];
    _citySelectedX.frame = CGRectMake(0, BVScreenH - 250, BVScreenW, 250);
    _citySelectedX.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_citySelectedX];
    
    // 1.创建pickView
    UIPickerView *pickerView  = [[UIPickerView alloc] init];
    pickerView.y = _citySelectedX.height - 216;
    pickerView.width = BVScreenW;
    pickerView.delegate = self;
    pickerView.dataSource = self;
    [_citySelectedX addSubview:pickerView];
    
    self.BusinessPickerViewX = pickerView;
    
    // 2.添加工具条
    UIView *toolView = [[UIView alloc] init];
    toolView.frame = CGRectMake(0, 0, BVScreenW, 40);
    toolView.backgroundColor = BVBackgroundLightGrayColor;
    [_citySelectedX addSubview:toolView];
    
    UIButton *cancelButton = [[UIButton alloc] init];
    cancelButton.frame = CGRectMake(0, 0, 60, 40);
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [cancelButton setTitleColor:BVBaseOrangeColor forState:UIControlStateNormal];
    cancelButton.titleLabel.font  = [UIFont systemFontOfSize:15];
    [cancelButton addTarget:self action:@selector(cancelBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [toolView addSubview:cancelButton];
    
    UIButton *correctButton = [[UIButton alloc] init];
    correctButton.frame = CGRectMake(BVScreenW - 60, 0, 60, 40);
    [correctButton setTitle:@"确定" forState:UIControlStateNormal];
    [correctButton setTitleColor:BVBaseOrangeColor forState:UIControlStateNormal];
    correctButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [correctButton addTarget:self action:@selector(corretButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [toolView addSubview:correctButton];
}
/**  隐藏pick*/
- (void)cancelBtnClick {
    [self.citySelectedX removeFromSuperview];
    self.citySelectedX= nil;
    [self.BusinessFX resignFirstResponder];
}

/**  pick选中赋值*/
- (void)corretButtonClick {
    
    // 返回拨键盘时被选定的行
    NSInteger row1 = [self.BusinessPickerViewX selectedRowInComponent:0];
    
    BVBusinessModelData * ModelData = self.BusinessArryX[row1];
    // 获得选中的商圈
    NSString *proviceName = ModelData.title;
    
    [self.BusinessFB setTitle:proviceName forState:UIControlStateNormal];
    self.SID = ModelData.dataIdentifier;
    
    // 移除pickerView
    [self.citySelectedX removeFromSuperview];
    self.citySelectedX = nil;
    [self.BusinessFX resignFirstResponder];
}

#pragma mark - UIPickerViewDelegate
// 告诉系统有多少列
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}
// 告诉系统有多少行
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return self.BusinessArryX.count;
}

// 告诉系统每一行显示什么内容
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    BVBusinessModelData * ModelData = self.BusinessArryX[row];
    return ModelData.title;
}
//获取商圈内容
-(void)getShangQuan{
    
    self.BusinessArryX = [[NSMutableArray alloc]init];
    NSString * city =  [[NSUserDefaults standardUserDefaults]objectForKey:@"city"];
    NSString *strUrl = [NSString stringWithFormat:@"%@/VegetableUserAPI/businesscircle?city=%@", Path,city];
    NSString *url = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [HttpTool get:url params:params success:^(id responseObj) {
        
        BVBusinessModelNSObject * NsObj = [BVBusinessModelNSObject modelObjectWithDictionary:responseObj];
        for (BVBusinessModelData * ModelData in NsObj.data) {
            [self.BusinessArryX addObject:ModelData];
        }
    } failure:^(NSError *error) {
        BVLog(@"请求失败");
    }];
}
#pragma mark --  button点击事件
- (void)confirmClick {
    // 拼接路径
    NSString *url = [NSString stringWithFormat:@"%@/VegetableUserAPI/doUserSaveAressById", Path];
    
    // 拼接参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"address_id"] = self.receviceAddress.ID;
    params[@"contact"] = self.nameF.text;
    params[@"mobile"] = self.phoneF.text;
    params[@"receive_address"] = self.addressF.text;
    params[@"detailed_address"] = self.detailAddressF.text;
    params[@"trade_id"] = self.SID;
    
    BVLog(@"%@,%@  %@",params[@"receive_address"],params[@"detailed_address"],params[@"trade_id"]);
    
    [HttpTool get:url params:params success:^(id responseObj) {
        if ([responseObj[@"code"] isEqualToString:@"1"]) {
            BVLog(@"修改地址成功-----%@", responseObj);
            if ([self.delegate respondsToSelector:@selector(modifyAddressDdiFinish:)]) {
                [self.delegate modifyAddressDdiFinish:self];
                ROOTNAVPOP
            }
        } else {
            BVLog(@"修改地址失败-----%@", responseObj);
        }
    } failure:^(NSError *error) {
        BVLog(@"请求失败-----%@", error);
    }];
}

#pragma mark -- UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if (self.addressF == textField) {
        BVBMKMapViewController *bmkMapVC = [[BVBMKMapViewController alloc] init];
        bmkMapVC.delegate = self;
        ROOTNAVPUSH(bmkMapVC, YES);
    }
}

#pragma mark -- BVBMKMapViewControllerDelegate
- (void)mapViewController:(BVBMKMapViewController *)bmkMap poiInfo:(BMKPoiInfo *)poiInfo {
    // 设置收获地址
    self.addressF.text = poiInfo.name;
    // 设置收货详细地址
//    self.detailAddressF.text = poiInfo.address;
    [self.detailAddressF becomeFirstResponder];
}

#pragma mark -- 设置导航栏
- (void)setupNav {
    self.title = @"修改地址";
    self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(backClick)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"xgdz_del.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(deleteAddress)];
}
#pragma mark 删除地址
- (void)deleteAddress{
    
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"" message:@"确定删除该收货地址？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction * sureAction = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        MBProgressHUD * hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hub.labelText = @"正在删除地址.....";
        hub.dimBackground = YES;
        
        [manager POST:@"http://app.jingcaibuy.com/VegetableUserAPI/doDeleteUserAddressById" parameters:@{@"address_id":self.receviceAddress.ID} success:^(NSURLSessionDataTask *task, id responseObject) {
            hub.labelText = @"删除成功";
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                hub.hidden = YES;
                if ([self.delegate respondsToSelector:@selector(modifyAddressDdiFinish:)]) {
                    [self.delegate modifyAddressDdiFinish:self];
                    ROOTNAVPOP
                }
            });
            
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            
            hub.labelText = @"删除失败";
            [hub hide:YES afterDelay:0.5f];
        }];
        
    }];
    
    [alertController addAction:cancleAction];
    [alertController addAction:sureAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark -- 返回
- (void)backClick {
    ROOTNAVPOP
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

@end
